
from flask import Blueprint, redirect,render_template, request, jsonify, session, url_for,flash
from app.models.HelpTopicElement import HelpTopicElement
from app.models.base import db
from app.models.helptopic import HelpTopic
from app.models.assignqV import AssignmentQ
from app.models.llmAnswer import LLMAnswer
from app.models.course import Course

helptopicBP = Blueprint('helptopic',__name__)

@helptopicBP.route('/search/<string:s_name>', methods=['GET','POST'])
def search(s_name):
    if request.method == 'GET':
        return render_template('searchelement.html',name=s_name)
    else:
        topic_title = request.form.get('title')  # 从表单中获取 title

        if not topic_title:
            return jsonify({'status': 'failed', 'message': 'Missing title parameter'}), 400

        try:
            # 查询指定 title 的主题
            # elements = db.session.query(HelpTopic).filter(HelpTopic.title == topic_title).all()
            elements = []
            Topic_title = HelpTopic.query.filter(HelpTopic.title.like(f'%{topic_title}%')).all()
            for tt in Topic_title:
                for answer in AssignmentQ.query.filter(AssignmentQ.Topic_id==tt.Topic_id).all():
                    for ass in LLMAnswer.query.filter(LLMAnswer.Q_id==answer.Q_id).all():
                        elements.append({
                            'Topic_id': tt.title,
                            'Q_id': ass.Q_id,
                            'LLM_question': answer.Q_Text,
                            'LLM_answer': ass.LLM_Answer,
                            'score': ass.Score,
                            'A_id': ass.A_id
                        })
            if elements:
                print(elements)
                return render_template('searchelement.html', results=elements,name=s_name)

            else:
                # 如果没有找到主题，返回主题未找到的消息
                return jsonify({'status': 'failed', 'message': 'Topic not found'}), 404
        except Exception as e:
            return jsonify({'status': 'failed', 'message': str(e)}), 500

@helptopicBP.route('/answer/<int:a_id>/<string:s_name>',methods=['GET','POST'])
def answer_detail(a_id,s_name):
    if request.method == 'GET':
        # 通过 A_id 查询对应的答案及其相关信息
        answer = LLMAnswer.query.get_or_404(a_id)
        if answer:
            # 通过 Q_id 查询相关的 AssignmentQ 对象
            question = AssignmentQ.query.get(answer.Q_id)
            if question:
                # 通过 CNumber 查询相关的 Course 对象
                course = Course.query.get(question.CNumber)

                # 确保在模板中可以使用这些信息
                return render_template('answer_detail_s.html', answer=answer, question=question, course=course,id=str(a_id),name=s_name)
            else:
                return "<h1>Question not found</h1>", 404
        return "<h1>Answer not found</h1>", 404
    else:
        if request.method == 'POST' and 'search_button' in request.form:
            search_field = request.form.get('topic_title')
            results = search()
            return render_template('helptopic.html', results=results, search_field=search_field,name=s_name)
